# This version of GApi use the googlemaps Python wrapper from http://py-googlemaps.sourceforge.net/

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from googlemaps import GoogleMaps
import json

@csrf_exempt
def main(request):
    origin = ""
    destination =""


    # posting = {}
    if request.method == 'POST':
        origin = request.POST.get('origin', False)
        destination = request.POST.get('destination', False)

        #to check what is in post
        #for key, value in request.POST.iteritems():
        #    posting.update({key : value})

    # using google api from googlemaps Python wrapper
    def getGoogle(origin, destination):
        direction = {}
        gmaps = GoogleMaps(api_key="AIzaSyAOG_azBIrP7rGEKJrtprrmov0qm348Uio" )
        dirs = gmaps.directions(origin, destination)
        time = dirs['Directions']['Duration']['html']
        dist = dirs['Directions']['Distance']['html']
        direction.update({'time': time})
        direction.update({'distance': dist})

        #route = dirs['Directions']['Routes']
        #i = 1
        #for step in route['Steps']:
        #    direction.update({str(i)+".": step['descriptionHtml']})
        #    i += 1

        dstep = []
        i =1
        for step in dirs['Directions']['Routes'][0]['Steps']:
            dstep.append(str(i) + ". "+ step['descriptionHtml'])
            i +=1

        direction.update({'direction': dstep})
        return direction

    response = getGoogle(origin, destination)
    return HttpResponse(json.dumps(response)) #not nicely printed...


